package com.ques.utils;

import com.ques.entity.MailMessage;

import javax.activation.DataHandler;
import javax.activation.FileDataSource;
import javax.mail.Message;
import javax.mail.MessagingException;
import javax.mail.Session;
import javax.mail.Transport;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeBodyPart;
import javax.mail.internet.MimeMessage;
import javax.mail.internet.MimeMultipart;
import java.io.File;
import java.io.UnsupportedEncodingException;
import java.util.List;
import java.util.Map;
import java.util.Properties;

/**
 * @author zq
 * @create 2019-11-24
 */
public class MailUtil {

    public Properties getProperties(String smtpHost, Integer port) {
        Properties props = new Properties();
        props.put("mail.smtp.host", smtpHost);
        props.put("mail.smtp.port", port);
        props.setProperty("mail.transport.protocol", "smtp");
        props.setProperty("mail.smtp.auth", "true");
        return props;
    }

    public void sendMail(MailMessage mailMessage) throws MessagingException, UnsupportedEncodingException {
        if (mailMessage.getAuthUser() == null || mailMessage.getAuthUser().isEmpty()) {
            throw new RuntimeException("邮件用户权限不能为空");
        }
        if (mailMessage.getAuthPassword() == null || mailMessage.getAuthPassword().isEmpty()) {
            throw new RuntimeException("邮件密码权限不能为空");
        }
        if (mailMessage.getToUsers() == null) {
            throw new RuntimeException("邮件接收列表不能为空");
        }
        if (mailMessage.getSmtpHost() == null) {
            throw new RuntimeException("邮件用户地址不能为空");
        }

        Session session = Session.getInstance(getProperties(mailMessage.getSmtpHost(), mailMessage.getPort()));

        Transport ts = session.getTransport();
        ts.connect(mailMessage.getSmtpHost(), mailMessage.getAuthUser(), mailMessage.getAuthPassword());
        Message message = createMail(session,mailMessage);
        ts.sendMessage(message, message.getAllRecipients());
        ts.close();

        System.out.println("发送完成");
    }

    public static MimeMessage createMail(Session session, MailMessage mailMessage) throws UnsupportedEncodingException, MessagingException {
        // 穿件邮件
        MimeMessage message = new MimeMessage(session);
//        设置 发送人、发送人名称
        message.setFrom(new InternetAddress(mailMessage.getAuthUser(), mailMessage.getFromName()));
//        设置接收人列表
        InternetAddress[] toUsers = new InternetAddress[mailMessage.getToUsers().size()];
//        message.set
        mailMessage.getToUsers().toArray(toUsers) ;
        message.setRecipients(Message.RecipientType.TO,toUsers);
        //设置抄送人列表
        if(mailMessage.getCC()){
            InternetAddress[] ccUsers = new InternetAddress[mailMessage.getCcUsers().size()];
            mailMessage.getCcUsers().toArray(ccUsers);
            message.setRecipients(Message.RecipientType.CC,ccUsers);
        }
        //设置密送人列表
        if(mailMessage.getBcc()){
            InternetAddress[] bccUsers = new InternetAddress[mailMessage.getBccUsers().size()];
            mailMessage.getBccUsers().toArray(bccUsers);
            message.setRecipients(Message.RecipientType.BCC,bccUsers);
        }

        //设置标题
        message.setSubject(mailMessage.getSubject());
        //设置正文
        MimeMultipart body = new MimeMultipart();
        MimeBodyPart content  = new MimeBodyPart();
        content.setContent(mailMessage.getContent(),"text/html;charset=utf-8");
        body.addBodyPart(content);
        //是否存在附件
        if(mailMessage.getEnclosure()){
            List<Map<String, String>> annexs = mailMessage.getAnnexs();
            for(Map<String,String> annexMap : annexs){
                MimeBodyPart annex = new MimeBodyPart();
                DataHandler dh1 = new DataHandler(new FileDataSource(new File(annexMap.get("filePath"))));
                annex.setDataHandler(dh1);
                annex.setFileName(annexMap.get("fileName"));
                body.addBodyPart(annex);
            }

            body.setSubType("mixed");
        }
        message.setContent(body);
        message.saveChanges();  //保存修改
        return message ;
    }
}
